/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.DatagramSocket;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import util.Message;

/**
 *
 * @author pol
 */
public class MessageSender {

    public MessageSender(UdpClient c, DatagramSocket s) {
        client = c;
        socket = s;
    }

    public boolean sendPacket(String data, InetAddress address) throws IOException {
        boolean ok = false;
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("H:mm:ss");
        Message msg;
        if (data.getBytes().length > Message.MAX_MESSAGE_SIZE) {
            msg = new Message(data.substring(0, 35), sdf.format(cal.getTime()));
        } else {
            msg = new Message(data, sdf.format(cal.getTime()));
        }
        byte[] buffer = msg.getBytes();
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, client.UDP_PORT);
        try {
            if (socket != null && !socket.isClosed()) {
                for (int i = 0; i < 4; i++) {
                    System.out.println(msg);
                    socket.send(packet);
                }
            }
            ok = true;
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return ok;
    }

    public boolean sendPacket(String data) throws IOException {
        return sendPacket(data, client.INTERNET_ADDRESS);
    }
    private UdpClient client;
    private DatagramSocket socket;
}
